package it.antonio.ilpizze.te.token;

import it.antonio.ilpizze.reflection.MethodAccessor;
import it.antonio.ilpizze.te.Filter;
import it.antonio.ilpizze.te.RenderCommand;
import it.antonio.ilpizze.te.util.ValueExtractor;

import java.util.Map;

public class CommandRenderCommand extends NodeRenderCommand{

	private String name;
	private String property;
	private String filterName;
	private String as;
	
	public CommandRenderCommand(NodeRenderCommand parent, String name, String property, String filterName, String as) {
		super(parent);
		this.name = name;
		this.property = property;
		this.filterName = filterName;
		this.as = as;
	}


	@Override
	public void contribute(Map<String, Object> model, Map<String, Filter> filters, StringBuffer buffer) {
		Object obj = model.get(name); 
		if(obj != null && property != null) {
			MethodAccessor method = ValueExtractor.getter(obj.getClass(), property);
			obj = method.invoke(obj);	
		}
		if(obj == null) return;
		
		
		// BOOLEAN
		if(obj instanceof Boolean){
			boolean b = (Boolean) obj;
			Filter f = filters.get(filterName);
			if(f != null){
				b = (Boolean) f.filter(b);
			} 
			
			if(b == true){
				contributeChildren(model, filters, buffer);
			}
			
			return;
		}
		
		// ITERABLE
		if(obj instanceof Iterable){
			if(as == null) throw new IllegalArgumentException("\"AS\" not defined for iterable");
			Iterable<?> it = (Iterable<?>) obj;
			
			Filter f = filters.get(filterName);
			if(f != null){
				it = (Iterable<?>) f.filter(it);
			} 
			
			for(Object iterated: it){
				model.put(as, iterated);
				contributeChildren(model, filters, buffer);
			}
			model.remove(as);	
			
			return;
		}
		
		// OBJECT
		Filter f = filters.get(filterName);
		if(f != null){
			obj = f.filter(obj);
		} 
		
		if(as != null){
			model.put(as, obj);
			contributeChildren(model, filters, buffer);
			model.remove(as);	
		} else {
			if(obj != null){
				contributeChildren(model, filters, buffer);
			}
		}
		
		
	}
}
